package com.qf.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsStorageMapper;
import com.qf.mapper.DtsTopicMapper;
import com.qf.pojo.DtsStorage;
import com.qf.pojo.DtsTopic;
import com.qf.service.DtsStorageService;
import com.qf.service.DtsTopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author bss
 * @version V1.0
 * @Project maven
 * @Package com.qf.service.impl
 * @Description:
 * @Date 2022/10/21 20:04
 */
@Service
public class DtsTopicServiceImpl implements DtsTopicService {
    @Autowired
    DtsTopicMapper topicMapper;
    @Autowired
    DtsStorageService storageService;
    @Autowired
    DtsStorageMapper storageMapper;


    @Override
    public Map<String, Object> selectPage(Integer page, Integer limit, String sort, String order, String title, String subtitle) {
        IPage<DtsTopic> iPage = new Page<>(page,limit);
        QueryWrapper<DtsTopic> wrapper = new QueryWrapper<>();
        if ("desc".equalsIgnoreCase(order)){
            wrapper.orderByDesc(sort);
        }else {
            wrapper.orderByAsc(sort);
        }

        if (!StringUtils.isEmpty(title)){
            wrapper.like("title", title);
        }
        if (!StringUtils.isEmpty(subtitle)){
            wrapper.like("subtitle",subtitle);
        }
        topicMapper.selectPage(iPage,wrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("total",iPage.getTotal());
        map.put("items",iPage.getRecords());
        return map;
    }

    @Override
    public void insert(DtsTopic topic) {
        topicMapper.insert(topic);
    }

    @Override
    public void update(DtsTopic topic) {
        topicMapper.updateById(topic);
    }

    @Override
    public void delete(DtsTopic topic) {
        topicMapper.deleteById(topic);
        LambdaQueryWrapper<DtsStorage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsStorage::getUrl,topic.getPicUrl());
        DtsStorage storage = storageMapper.selectOne(wrapper);
        storageService.delete(storage);
    }
}
